#pragma once

#include "Sock.hpp"
#include <sys/select.h>
#include <poll.h>

using namespace std;

const uint16_t defaultport = 8899;
const int fd_max_num = 64;
const int defaultfd = -1;
int nonevent = 0;

class PollServer
{
public:
    PollServer(uint16_t port = defaultport)
        : _port(port)
    {
        for (int i = 0; i < fd_max_num; i++)
        {
            _event_fds[i].fd = defaultfd;
            _event_fds[i].events = nonevent;
            _event_fds[i].revents = nonevent;
        }
    }
    ~PollServer()
    {
        _listensock.Close();
    }

    bool Init()
    {
        _listensock.Socket();
        _listensock.Bind(_port);
        _listensock.Listen();

        return true;
    }

    void Accepter()
    {
        // 监听事件就绪可以获取连接了
        uint16_t clientport;
        string clientip;
        int sock = _listensock.Accept(&clientip, &clientport);
        if (sock < 0)
            return;
        cout << "accept success ,fd:" << sock << ",clientip:" << clientip << ",clientport:" << clientport << endl;

        // 可以直接读取吗，不可以，读取事件没就绪，还需要把sock放入到select中
        int pos = 1;
        for (; pos < fd_max_num; pos++)
        {
            if (_event_fds[pos].fd != defaultfd)
                continue;
            else
                break;
        }
        // 出循环有2个原因，1.等于defaultfd 2.pos =fd_max_num
        if (pos == fd_max_num)
        {
            cout << "server is full ,close fd:" << sock << endl;
            close(sock);
            // 或者扩容
        }
        else
        {
            _event_fds[pos].fd = sock;
            _event_fds[pos].events = POLLIN;
            _event_fds[pos].revents = nonevent;
            // 打印所有事件
            PrintFd();
        }
    }

    void Recver(int fd, int pos)
    {
        char buffer[1024];
        ssize_t n = read(fd, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = 0;
            cout << "get a message: " << buffer << endl;
        }
        else if (n == 0)
        {
            cout << "sockfd close ,fd:" << fd << endl;
            close(fd);
            _event_fds[pos].fd = defaultfd;
        }
        else
        {
            cout << "read failed ,fd:" << fd << endl;
            close(fd);
            _event_fds[pos].fd = defaultfd;
        }
    }
    void Dispatcher()
    {
        // 遍历fd_array，看哪个fd的事件就绪
        for (int i = 0; i < fd_max_num; i++)
        {
            int fd = _event_fds[i].fd;
            if (fd == defaultfd)
                continue;

            // 有两个事件1.监听事件就绪 2.读事件就绪
            if (_event_fds[i].revents & POLLIN)
            {
                // 处理监听就绪事件
                if (fd == _listensock.Fd())
                {
                    Accepter(); // 连接管理器
                }
                // 读事件就绪
                else
                {
                    Recver(fd, i);
                }
            }
        }
    }

    void PrintFd()
    {
        cout << "online fd list : ";
        for (int i = 0; i < fd_max_num; i++)
        {
            if (_event_fds[i].fd != defaultfd)
                cout << _event_fds[i].fd << " ";
        }
        cout << endl;
    }

    void Start()
    {
        int timeout = 3000;
        _event_fds[0].fd = _listensock.Fd();
        _event_fds[0].events = POLLIN; // 关注读事件
        while (1)
        {
            int n = poll(_event_fds, fd_max_num, timeout);
            switch (n)
            {
            case 0:
                cout << "time out..." << endl;
                break;
            case -1:
                cout << "select error" << endl;
                break;
            default:
                cout << "get a link !!!" << endl;
                Dispatcher();
                break;
            }
        }
    }

private:
    Sock _listensock;
    uint16_t _port;
    // int fd_array[fd_max_num];
    struct pollfd _event_fds[fd_max_num];
};